﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace pdfer.Filters
{
    internal class ASCII85DecodeFilter : IFilter
    {
        /// <summary>
        /// <inheritdoc/>
        /// 线程安全的实现
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public Byte[] Decode(ReadOnlySpan<Byte> input)
        {
            using var output = new MemoryStream();
            var i = 0;
            var count = input.Length;
            if (input[0] == '<' && input[1] == '~')
            {
                i = 2;
            }
            if (input[^1] == '>' && input[^2] == '~')
            {
                count -= 2;
            }
            var _ = new UInt32[5];
            var len = 4;
            var _tmp = new Span<UInt32>(_);
            var empties = new Byte[4];
            for(; i < count; i++)
            {
                var data = input[i];
                if(data == 'z')//122
                {
                    // 空字符
                    // 不应该出现在组的中间
                    output.Write(empties);
                    continue;
                }
                if (data < 33 || data > 117)
                {
                    throw new Exception("非法字符：ASCII85Decode.");
                }
                // 33 -> 117
                // ! -> u
                // 0b0101_0100
                len = 4;
                for (var j = 0; j < 5; i++, j++)
                {
                    if (data is (0 or 9 or 10 or 12 or 13 or 32)) 
                    {
                        _tmp[j] = 84;
                        len--;
                        // 原始字符长度不是4的整数倍
                    }
                    else
                    {
                        _tmp[j] = (UInt32)(input[i] - '!');
                    }
                }
                uint value = _tmp[0] * 85 * 85 * 85 * 85 +
                             _tmp[1] * 85 * 85 * 85 +
                             _tmp[2] * 85 * 85 +
                             _tmp[3] * 85 +
                             _tmp[4];
                var bs = BitConverter.GetBytes(value).Reverse().Take(len - 1).ToArray();
                output.Write(bs);

            }
            return output.ToArray();
        }

        public Byte[] Encode(ReadOnlySpan<Byte> input)
        {
            throw new NotImplementedException();
        }
    }
}
